package com.itjin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itjin.model.domain.dto.AddUserDTO;
import com.itjin.model.domain.dto.EditUserDTO;
import com.itjin.model.domain.dto.ChangePasswordDTO;
import com.itjin.model.domain.entity.User;
import com.itjin.model.result.PageResult;
import com.itjin.model.domain.vo.UserVO;
import com.itjin.model.result.Result;
import com.itjin.service.MangerService;
import com.itjin.service.UserService;
import lombok.extern.slf4j.Slf4j;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import static com.itjin.contant.UserConstant.DEFAULT_ROLE;
import static com.itjin.contant.UserConstant.SALT;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/manager")
@Tag(name = "管理员控制器")
@Slf4j
public class MangerController {

    @Resource
    private UserService userService;

    @Resource
    private MangerService mangerService;

    /**
     * 添加用户
     * 
     * @param addUserDTO 添加用户DTO
     * @param request    请求
     * @return 用户VO
     */
    @Operation(summary = "添加用户")
    @PostMapping("/add")
    public Result<UserVO> addUser(@RequestBody AddUserDTO addUserDTO, HttpServletRequest request) {
        // 1. 验证管理员权限
        if (!isAdmin(request)) {
            return Result.failure(403, "无权限");
        }

        try {
            // 2. 添加用户
            boolean result = mangerService.addUser(addUserDTO);
            if (!result) {
                return Result.failure(500, "添加用户失败");
            }

            // 3. 查询新增的用户信息
            User user = userService.getOne(new QueryWrapper<User>()
                    .eq("userAccount", addUserDTO.getUserAccount())
                    .last("LIMIT 1"));

            // 4. 转换为VO对象返回
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return Result.success(userVO);
        } catch (RuntimeException e) {
            log.error("添加用户失败: {}", e.getMessage());
            return Result.failure(400, e.getMessage());
        } catch (Exception e) {
            log.error("添加用户失败", e);
            return Result.failure(500, "添加用户失败: " + e.getMessage());
        }
    }

    /**
     * 查询单个用户
     * 
     * @param username 用户名
     * @param request  请求
     * @return 用户列表
     */
    @Operation(summary = "查询用户")
    @GetMapping("/search")
    public List<User> searchUsers(String username, HttpServletRequest request) {
        // 健全：仅仅管理员可以查询
        if (!isAdmin(request)) {
            return new ArrayList<>();
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username);
        }
        List<User> userList = userService.list(queryWrapper);
        return userList.stream().peek(user -> user.setUserPassword(null)).collect(Collectors.toList());
    }

    /**
     * 删除用户
     * 
     * @param id      用户ID
     * @param request 请求
     * @return 是否删除成功
     */
    @Operation(summary = "删除用户")
    @DeleteMapping("/delete/{id}")
    public Result deleteUser(@PathVariable int id, HttpServletRequest request) {
        try {
            if (!isAdmin(request)) {
                return Result.failure(400, "无权限");
            }
            if (id <= 0) {
                return Result.failure(400, "无效用户");
            }
            boolean isDeleted = userService.removeById(id);
            if (isDeleted) {
                return Result.success("删除成功");
            } else {
                return Result.failure(400, "删除失败");
            }
        } catch (Exception e) {
            return Result.failure(500, "服务器错误: " + e.getMessage());
        }
    }

    /**
     * 查询用户列表
     * 
     * @param page    当前页
     * @param size    每页大小
     * @param keyword 搜索关键词
     * @param request 请求
     * @return 用户列表
     */
    @Operation(summary = "查询用户列表")
    @GetMapping("/userlist")
    public PageResult<UserVO> userList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String keyword,
            HttpServletRequest request) {

        // 1. 验证管理员权限
        if (!isAdmin(request)) {
            return new PageResult<>();
        }

        try {
            // 2. 查询分页数据
            Page<User> userPage = mangerService.listUsersByPage(page, size, keyword);

            // 3. 构建返回结果
            PageResult<UserVO> result = new PageResult<>();
            result.setCode(200);
            result.setCurrentPage((int) userPage.getCurrent());
            result.setPageSize((int) userPage.getSize());
            result.setTotal(userPage.getTotal());
            result.setTotalPages((int) userPage.getPages());

            // 4. 转换VO
            List<UserVO> voList = userPage.getRecords().stream().map(user -> {
                UserVO vo = new UserVO();
                BeanUtils.copyProperties(user, vo);
                return vo;
            }).collect(Collectors.toList());

            result.setData(voList);
            return result;
        } catch (Exception e) {
            log.error("查询用户列表失败", e);
            return new PageResult<>();
        }
    }

    /**
     * 编辑用户
     * 
     * @param editUserDTO 编辑用户DTO
     * @param request     请求
     * @return 编辑结果
     */
    @Operation(summary = "编辑用户")
    @PutMapping("/edit")
    public Result<UserVO> editUser(@RequestBody EditUserDTO editUserDTO, HttpServletRequest request) {
        // 1. 验证管理员权限
        if (!isAdmin(request)) {
            return Result.failure(403, "无权限");
        }

        try {
            // 2. 参数校验
            if (editUserDTO == null || editUserDTO.getId() == null) {
                return Result.failure(400, "参数错误");
            }

            // 3. 更新用户
            boolean result = mangerService.editUser(editUserDTO);
            if (!result) {
                return Result.failure(500, "编辑用户失败");
            }

            // 4. 查询更新后的用户信息
            User user = userService.getById(editUserDTO.getId());
            if (user == null) {
                return Result.failure(404, "用户不存在");
            }

            // 5. 转换为VO对象返回
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return Result.success(userVO);
        } catch (RuntimeException e) {
            log.error("编辑用户失败: {}", e.getMessage());
            return Result.failure(400, e.getMessage());
        } catch (Exception e) {
            log.error("编辑用户失败", e);
            return Result.failure(500, "编辑用户失败: " + e.getMessage());
        }
    }

    /**
     * 重置用户密码
     * 
     * @param id      用户ID
     * @param request 请求
     * @return 重置结果
     */
    @Operation(summary = "重置用户密码")
    @PutMapping("/password/reset/{id}")
    public Result<String> resetUserPassword(@PathVariable Integer id, HttpServletRequest request) {
        // 1. 验证管理员权限
        if (!isAdmin(request)) {
            return Result.failure(403, "无权限");
        }

        try {
            // 2. 重置密码
            boolean result = mangerService.resetUserPassword(id);
            if (result) {
                return Result.success("密码重置成功");
            } else {
                return Result.failure(500, "密码重置失败");
            }
        } catch (RuntimeException e) {
            log.error("密码重置失败: {}", e.getMessage());
            return Result.failure(400, e.getMessage());
        } catch (Exception e) {
            log.error("密码重置失败", e);
            return Result.failure(500, "密码重置失败: " + e.getMessage());
        }
    }

    /**
     * 修改用户密码
     * 
     * @param changePasswordDTO 修改密码DTO
     * @param request           请求
     * @return 修改结果
     */
    @Operation(summary = "修改用户密码")
    @PutMapping("/password/change")
    public Result<String> changePassword(@RequestBody ChangePasswordDTO changePasswordDTO,
            HttpServletRequest request) {
        // 1. 验证管理员权限
        if (!isAdmin(request)) {
            return Result.failure(403, "无权限");
        }

        try {
            // 2. 修改密码
            boolean result = mangerService.changePassword(
                    changePasswordDTO.getId(),
                    changePasswordDTO.getCurrentPassword(),
                    changePasswordDTO.getNewPassword());

            if (result) {
                return Result.success("密码修改成功");
            } else {
                return Result.failure(500, "密码修改失败");
            }
        } catch (RuntimeException e) {
            log.error("密码修改失败: {}", e.getMessage());
            return Result.failure(400, e.getMessage());
        } catch (Exception e) {
            log.error("密码修改失败", e);
            return Result.failure(500, "密码修改失败: " + e.getMessage());
        }
    }

    /**
     * 更新用户标签
     * 
     * @param userId  用户ID
     * @param tags    标签列表
     * @param request 请求
     * @return 更新结果
     */
    @Operation(summary = "更新用户标签")
    @PutMapping("/tags/{userId}")
    public Result<UserVO> updateUserTags(@PathVariable Integer userId,
            @RequestBody List<String> tags,
            HttpServletRequest request) {
        // 1. 验证管理员权限
        if (!isAdmin(request)) {
            return Result.failure(403, "无权限");
        }

        try {
            // 2. 参数校验
            if (userId == null || userId <= 0) {
                return Result.failure(400, "无效用户ID");
            }

            if (tags == null) {
                tags = new ArrayList<>();
            }

            // 3. 更新用户标签
            boolean result = userService.updateUserTags(userId, tags);
            if (!result) {
                return Result.failure(500, "更新用户标签失败");
            }

            // 4. 查询更新后的用户信息
            User user = userService.getById(userId);
            if (user == null) {
                return Result.failure(404, "用户不存在");
            }

            // 5. 转换为VO对象返回
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return Result.success(userVO);
        } catch (RuntimeException e) {
            log.error("更新用户标签失败: {}", e.getMessage());
            return Result.failure(400, e.getMessage());
        } catch (Exception e) {
            log.error("更新用户标签失败", e);
            return Result.failure(500, "更新用户标签失败: " + e.getMessage());
        }
    }

    /**
     * 校验管理员权限
     */
    private boolean isAdmin(HttpServletRequest request) {
        // User currentUser = (User) request.getAttribute("currentUser");
        // log.debug("当前请求用户信息：{}", currentUser); // 添加调试日志
        //
        // if (currentUser == null) {
        // log.warn("未授权访问尝试：请求未携带有效凭证");
        // return false;
        // }
        //
        // // 3. 检查用户角色
        // if (!(ADMIN_ROLE == currentUser.getUserRole())) {
        // log.warn("权限拒绝：用户[ID:{}] 尝试访问管理员接口", currentUser.getId());
        // return false;
        // }
        //
        // // 4. 附加检查用户状态
        // if (currentUser.getUserStatus() != 0) {
        // log.warn("账户状态异常：用户[ID:{}] 状态为 {}", currentUser.getId(),
        // currentUser.getUserStatus());
        // return false;
        // }

        return true;
    }
}
